// 02login/02regUser/regUser.js
var co = require('../../resource/js/common.js')
var app = getApp()
var _this, _data

var _inviter_User_ID = 0
//首页输入的手机，
var _inputPhone
//验证码
var _sms_Code
//联盟id
var _unionid
//openid
var _openid
//参数
var _opt = {}
//是否关闭倒计时
var isCloseCountDown = false
//参数信息
var paramInfo = {}
//表单ID
var _form_id

Page({
   data: {
      //是否注册过
      isRegistered: '',
      //验证是否ok
      verified_Ok: 0,
      //商家公司名称
      busLicenseName: '',
      //法人名称
      legalPersonName: '',
      //微信实名是否法人名称
      wxRealName_is_legalPersonName: 0,
      //验证到手机号码
      verified_Phone: '',
      //验证码
      getSmsCodeText: '',
      //商家信息
      shopInfo: '',
   },

   onLoad: function(opt) {
      _this = this
      _data = this.data
      _unionid = wx.getStorageSync('unionid')
      console.log('_unionid', _unionid)
      _this.setData({
         isRegistered: '',
         verified_Ok: 0,
         getSmsCodeText: '获取验证码'
      })

      //处理页面参数
      _this.doOptData(opt)
   },

   onUnload: function() {
      _opt = {}
      paramInfo = {}
   },

   //处理页面数据
   doOptData: function(opt) {
      if (opt && opt.scene) {
         //参数列表
         var paramArr = opt.scene.split('.')
         var len = paramArr.length
         for (var i = 0; i < len; i += 2) {
            //获取key值
            var key = paramArr[i]
            //获取value值
            _opt[key] = paramArr[i + 1]
         }
         console.log('opt.sence', opt.scene)
         console.log('paramArr', paramArr)
         console.log('len', len)
         console.log('_opt', _opt)
         _inviter_User_ID = _opt.UserID ? _opt.UserID : 0
      }
      //获取商家信息
      _this.getShopInfo()
   },

   //获取商家信息(非法人的商家信息)
   getShopInfo: function() {
      //获取商家信息的邀请人(该商家信息中的法人id为0, 即:Legal_Person_User_ID = 0)
      var url = 'jyhs/Admin/getInfo'
      co.getShareApi(url, {
         Biz_ID: _opt.BizID
      }, function(res) {
         var userInfo = res.data
         if (!userInfo.Is_Auth || (userInfo.Is_Auth && userInfo.Legal_Person_User_ID)) {
            //跳转到认证页面
            co.redirectTo('/03admin/12bizAuth/bizAuth', 10)
         }
         //法人未认证
         else {
            //获取营业执照信息
            _this.getAuthInfo()
         }
         _this.setData({
            shopInfo:res.data
         })
         console.log('res.dataOFshop',res.data)
      })
   },

   //获取营业执照认证信息
   getAuthInfo: function() {
      co.getShareApi('biz/Bizmg/getAuthInfo', {
         Biz_ID: _opt.BizID
      }, function(res) {
         paramInfo.legalPersonName = res.data.LegalPersonName
         paramInfo.busLicenseName = res.data.Name
         // _this.setData({
         //    legalPersonName: res.data.LegalPersonName,
         //    busLicenseName: res.data.Name
         // })

         //去自动登录
         _this.toAutoLogin()
      })
   },

   //准备自动登录
   toAutoLogin: function() {
      //unionid为空
      if (co.empty(_unionid)) {
         //微信登录
         app.wxLogin(function(res) {
            if (co.empty(res.unionid)) {
               _openid = res.openid
            } else {
               _unionid = res.unionid;
            }
            _this.autoLogin()
         })
      }
      //unionid不为空
      else {
         _this.autoLogin()
      }
   },

   //自动登录
   autoLogin: function() {
      var param = {}
      if (co.empty(_unionid)) {
         param.openid = _openid
      } else {
         param.unionid = _unionid
      }
      //获取用户信息(法人用户信息)
      co.getShareApi("jyhs/Usermg/getUserInfo", param, function(res) {
         if (res.code == 0) {
            var d = res.data
            //var biz_list = co.empty(d.biz_list) ? [] : d.biz_list
            //处理用户数据
            _this.doUserData(d, d.User_Mobile)
            console.log('res.data',res.data)
         } else {
            //处理数据
            _this.doUserData('', '')
         }
      })
   },

   //处理用户数据
   doUserData: function(userInfo, mobile) {
      //获取用户信息(法人用户信息)
      app.Data.userInfo = userInfo

      //判断商家信息集合
      // if (biz_list.length) {
      //    app.Data.shopInfo = biz_list[0]
      // }
      // _this.setData({
      //    //user: userInfo,
      //    //shopInfo: biz_list,
      //    verified_Ok: _this.checkPhone(mobile),
      //    verified_Phone: mobile,
      // })

      if (_this.checkPhone(mobile)) {
         paramInfo.legalPerson_Info = userInfo
         //刷新页面
         _this.setData({
            isRegistered: 1,
            busLicenseName: paramInfo.busLicenseName,
            legalPersonName: paramInfo.legalPersonName,
            wChatImg: userInfo.User_HeadImg,
            wChatName: userInfo.User_NickName,
            // shopInfo: app.Data.shopInfo,
         })
      } else {
         _this.setData({
            isRegistered: 0,
            verified_Ok: 0,
            verified_Phone: mobile,
         })
      }
   },

   //检查手机格式
   checkPhone: function(phone) {
      var phoneNumber = phone ? phone : _inputPhone
      var rule = /^1[0-9]{10}$/
      //console.log('【checkPhone(phone)==】' + phoneNumber)
      return rule.test(phoneNumber) ? 1 : 0
   },

   //一键获取微信认证手机
   getPhoneNumber: function(e) {
      app.decryptWxInfoData(e.detail, function(res) {
         _this.setData({
            verified_Ok: 1,
            verified_Phone: res.phoneNumber,
         })
      })
   },

   //输入手机
   inputPhone: function(e) {
      _inputPhone = e.detail.value
      console.log('【inputPhone】===' + _inputPhone)
   },

   //换个手机
   changePhone: function(e) {
      _this.setData({
         verified_Ok: 0,
         verified_Phone: '',
      })
   },

   //输入验证码
   inputCode: function(e) {
      console.log('输入码==' + e.detail.value)
      var input_sms_Code = e.detail.value
      //判断验证码
      if (input_sms_Code.length > 6 ||
         (input_sms_Code.length == 6 && input_sms_Code != _sms_Code)) {
         co.toastAllText('验证码不正确')
      } else if (input_sms_Code == _sms_Code) {
         isCloseCountDown = true
         _this.setData({
            verified_Ok: 1,
            verified_Phone: _data.verified_Phone,
         })
      }
   },

   //获取短信验证码
   getPhoneCode: function(e) {
      //判断手机格式
      if (!_this.checkPhone(_inputPhone)) {
         co.toastAllText('手机号格式不正确2')
         return
      }
      _data.verified_Phone = _inputPhone
      //获取验证码
      co.getShareApi('api/Sms/getPhoneCode', {
         mobile: _data.verified_Phone,
         type: 'user_reg'
      }, function(res) {
         if (res.code == 0) {
            _sms_Code = res.data.Sms_Code
            var second = 90
            _this.setData({
               getSmsCodeText: '重新获取(' + second + '秒)'
            })
            _this.countDown(second)
         } else {
            co.toastAllText(res.msg)
         }
      })
   },

   //倒计时
   countDown: function(time) {
      setTimeout(function() {
         if (!isCloseCountDown && time > 1) {
            //显示倒计时
            _this.setData({
               getSmsCodeText: '重新获取(' + time + '秒)'
            })
            time--
            //递归
            _this.countDown(time)
         } else {
            isCloseCountDown = false
            _this.setData({
               getSmsCodeText: '重新获取'
            })
         }
      }, 1000);
   },

   //点击授权
   getWxUserInfo: function(e) {
      console.log('e====', e);
      var param = e.detail
      //判断电话号码输入是否一致
      // if (_inputPhone != _data.verified_Phone) {
      //    co.toastAllText('你输入的手机号码与之前不一致')
      //    return
      // }
      //获取用户号码
      param.User_Mobile = _data.verified_Phone
      //获取邀请人ID(邀请认证的人)
      //param.Owner_Id = _inviter_UserID
      wx.setStorageSync('Owner_Id', _inviter_User_ID)
      //获取session_key
      var session_key = wx.getStorageSync('session_key')
      wx.showLoading({
         title: '正在授权...',
      })
      //session_key为空
      if (co.empty(session_key)) {
         //进行登录
         app.wxLogin(function(res) {
            console.log("【wxLogin登录结果】===", res)
            if (res.code == 0) {
               _this.getWxUserInfoData(param)
            } else {
               wx.hideLoading()
               co.toastAllText(res.msg)
            }
         })
         return
      }
      _this.getWxUserInfoData(param)
   },

   //提示手机认证
   showToast: function(e) {
      co.toastAllText('请先手机认证')
   },

   //获取用户信息(获取用户 或注册 或更新)
   getWxUserInfoData: function(param) {
      //解密和获取微信用户信息(如果用户不存在,则自动注册)
      app.decryptWxUserInfoData(param, function(res) {
         console.log('res====', res);
         wx.hideLoading()
         co.toastAllText(res.msg)
         if (res.code == 0) {
            //打款验证法人姓名
            //_this.checkLegalPersonName(res.data, param.userInfo)
            //_this.checkLegalPersonName(res.data)
            //获取法人信息
            paramInfo.legalPerson_Info = res.data
            //获取微信用户信息
            var wx_userInfo = param.userInfo
            //刷新页面
            _this.setData({
               isRegistered: 1,
               busLicenseName: paramInfo.busLicenseName,
               legalPersonName: paramInfo.legalPersonName,
               wChatImg: wx_userInfo.avatarUrl,
               wChatName: wx_userInfo.nickName,
               // shopInfo: app.Data.shopInfo,
            })
         }
         // else {
         //    wx.hideLoading()
         //    co.toastAllText(res.msg)
         // }
      })
   },

   //打款验证法人姓名
   checkLegalPersonName: function(e) {
      console.log('e========', e)
      _form_id = e.detail.formId
      //获取商家余额
      //var balance = _data.shopInfo.Biz_Money
      //判断商家余额
      // if (balance < 1) {
      //    //提示
      //    co.confirm('', '您的商家零钱余额不足,请充值!',
      //       '取消', '确定',
      //       function(res) {})
      //    return
      // }
      var appid = app.Data.app.appid
      var legalPerson_Info = paramInfo.legalPerson_Info
      wx.showLoading({
         title: '正在认证中...',
      })
      co.getShareApi('api/Wxpay/toWxWallet', {
         Biz_ID: _opt.BizID,
         Biz_PayPassword: app.Data.app.appid + 'bizlegalpersonauth',
         amount: 0.30,
         desc: '提现验证法人真实姓名',
         mch_appid: appid,
         //paySecret: 'bShYjNaUyIzGnEhSiAzIlIsNaHuOhZuF',
         openid: legalPerson_Info.Wx_Openid[appid],
         real_name: paramInfo.legalPersonName,
         // mchid: '1504097781',
         Payer: 'Biz_91',
         Pay_From: '91_pay'
      }, function(res) {
         console.log('res===', res)
         if (res.code == 0) {
            //法人认证保存 
            _this.saveAuthLegalPerson(legalPerson_Info)
            _this.setData({
               wxRealName_is_legalPersonName: 1
            })
         } else {
            wx.hideLoading()
            //co.toastAllText(res.msg)
            if (res.msg.indexOf('真实姓名不一致') < 0) {
               co.Modal(res.msg)
            } else {
               co.Modal('本微信实名不是法人姓名，法人认证失败！请用法人姓名的微信重新认证')
            }
         }
      })
   },

   //商家认证保存(法人认证保存)
   saveAuthLegalPerson: function(legalPerson_Info) {
      var param = {
         Biz_ID: _opt.BizID,
         //法人id
         Legal_Person_User_ID: legalPerson_Info.User_ID
      }
      co.getShareApi("biz/Bmg/saveAuthLegalPerson", param, function(res) {
         console.log("【res=============】", res)
         if (res.code == 0) {
            _this.addUserMoneyRecord()
         } else {
            wx.hideLoading()
            co.Modal(res.msg)
         }
      })
   },

   //添加用户资金记录(提成)
   addUserMoneyRecord: function() {
      var param = {
         User_ID: app.Data.shopInfo.Inviter_User_ID,
         Abstract: '邀请' + app.Data.shopInfo.Biz_Account + '的第一笔提成',
         Payer: 'Biz_91',
         Money: 18.88,
         Pay_From: '91_pay',
         Pay_To: '91_pay',
         Pay_For: 'Biz_' + app.Data.shopInfo.Biz_ID
      }
      co.addMoneyRecord_User(param, function(res) {
         console.log('res===', res)
         if (res.code == 0) {
            _this.getInviteInfo(param.Money)
         } else {
            wx.hideLoading()
            //co.toastAllText(res.msg)
            co.Modal(res.msg)
         }
      })
   },

   //获取邀请人OpenID(介绍人)
   getInviteInfo: function(money) {
      co.getShareApi('user/Mg/getUserInfo', {
         User_ID: app.Data.shopInfo.Inviter_User_ID,
         field: 'Wx_Openid'
      }, function(res) {
         wx.hideLoading()
         //co.toastAllText(res.msg)
         if (res.code == 0) {
            //发送消息
            var openid = res.data.Wx_Openid.wxa087ce51079f066e
            if (openid) {
               _this.sendWeChatMessage(openid, money)
               _this.sendWxAppMessage(money)
            }
            co.confirm('', '法人微信真实姓名认证成功', '', '确定', function(_res) {
               //跳转到认证页面
               co.redirectTo('/03admin/12bizAuth/bizAuth', 1000)
            })
         } else {
            co.Modal(res.msg)
         }
      })
   },

   //推送微信模板消息(公众号)
   sendWeChatMessage: function(openID, money) {
      //被邀请人的shopInfo
      var shopInfo = app.Data.shopInfo
      //被邀请人的userInfo(法人的userInfo)
      var userInfo = app.Data.userInfo
      //第一笔和第二笔提成金额
      var money1 = money
      var money2 = 48.88
      co.getShareApi('api/Weixin/sendTemplateMsg', {
         appid: 'wxa087ce51079f066e',
         secret: '0c3c47175610bf54df25837e359e5eb6',
         openid: openID,
         template_id: 'GJNO5bl1RKZgPmFF8Dep3O24vjG9dE0v8545B2NnHqc',
         title_value: '你邀请商家入驻【爱共享·码上点】，获得一份的第一笔提成。\n点击详情->登录->我的293零钱->提现(可秒到微信钱包)',
         title_color: '#ff0000',
         k1_value: userInfo.User_NickName,
         k1_color: '#1296db',
         k2_value: shopInfo.Biz_Account,
         k2_color: '#1296db',
         k3_value: '￥' + money + '元',
         k3_color: '#1296db',
         k4_value: money1 + '元 + ' + money2 + '元 + 长期分红',
         k4_color: '#ff0000',
         k5_value: co.getFormatDate(2),
         k5_color: '#1296db',
         remark_value: '(1)邀请提成' + money1 + '元；\n(2)商家启用提成' + money2 + '元；\n(3)商家长期续用分红。',
         remark_color: '#ff0000',
         miniprogram: {
            appid: "wxd352f5d5fc71beaa",
            pagepath: "/03myCenter/01myCenter/myCenter"
         }
      }, function(res) {
         console.log('res====', res)
         //co.toastAllText(res.msg)
      })
   },

   //小程序推送模板消息
   sendWxAppMessage(money) {
      //被邀请人的shopInfo
      var shopInfo = app.Data.shopInfo
      //被邀请人的userInfo(法人的userInfo)
      var userInfo = app.Data.userInfo
      co.getShareApi('api/Weixin/sendWxAppTemplateMsg', {
         appid: app.Data.app.appid,
         secret: app.Data.app.secret,
         openid: userInfo.Wx_Openid.wx91ba1f8a10ec2762,
         formId: _form_id,
         page: '01login/reg/bizReg',
         template_id: 'ydBjdufDCeobHiiGMaExM-jjm-YBfwSj0OIZQZ7DAbs',
         keyword1: '爱共享293·码上点',
         keyword2: '你邀请的' + shopInfo.Biz_Account + '法人已认证, 已获取第一笔提成' + money + '元',
         keyword3: '￥' + money + '元',
         keyword4: co.getFormatDate(2),
         keyword5: '点击详情->登录->我的293零钱->提现(可秒到微信钱包)',
      }, function(res) {
         console.log('res====', res)
      })
   }
})